﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Reflection;

namespace TaoLeH.Helper
{
    /// <summary>
    /// 实体类转换帮助类
    /// 作者：leev
    /// 时间：2018-12-18
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class ModelHandler<T> where T : new()
    {
        #region 实体类转Hashtable
        /// <summary>
        /// 实体类转Hashtable
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static Hashtable TransforClass(T value)
        {
            Hashtable ht = new Hashtable();
            foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
            {
                ht.Add(propertyInfo.Name.ToLower(), propertyInfo.GetValue(value, null));
            }
            return ht;
        }

        #endregion

        #region DataTable转换成实体类

        /// <summary>  
        /// 填充对象列表：用DataSet的第index个表填充实体类
        /// </summary>  
        public List<T> FillModel(DataSet ds, int index = 0)
        {
            if (ds == null || ds.Tables.Count <= index || ds.Tables[index].Rows.Count == 0)
            {
                return null;
            }
            else
            {
                return FillModel(ds.Tables[index]);
            }
        }

        /// <summary>  
        /// 填充对象列表：用DataTable填充实体类
        /// </summary>  
        public List<T> FillModel(DataTable dt)
        {
            if (dt == null || dt.Rows.Count == 0)
            {
                return null;
            }
            List<T> modelList = new List<T>();
            foreach (DataRow dr in dt.Rows)
            {
                var model = FillModel(dr);
                modelList.Add(model);
            }
            return modelList;
        }

        /// <summary>  
        /// 填充对象：用DataRow填充实体类
        /// </summary>  
        public T FillModel(DataRow dr)
        {
            if (dr == null)
            {
                return default(T);
            }

            T model = new T();

            for (int i = 0; i < dr.Table.Columns.Count; i++)
            {
                PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName);
                if (propertyInfo != null && dr[i] != DBNull.Value)
                {
                    if (propertyInfo.PropertyType.IsGenericType && propertyInfo.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
                        propertyInfo.SetValue(model, Convert.ChangeType(dr[i], Nullable.GetUnderlyingType(propertyInfo.PropertyType)), null);
                    else
                        propertyInfo.SetValue(model, Convert.ChangeType(dr[i], propertyInfo.PropertyType), null);
                }
            }
            return model;
        }

        #endregion
    }
}